package com.itheima.reggie.controller;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Dish;
import com.itheima.reggie.service.DishService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;


@RestController
public class DishController {
    @Autowired
    DishService dishService;

    @Autowired
    RedisTemplate redisTemplate;

    //查询菜品管理的全部列表
    @GetMapping("/dish/page")
    public ResultInfo findByLimit(
            @RequestParam(value = "page",defaultValue ="1") Integer pageNum,
            @RequestParam(value = "pageSize",defaultValue = "10") Integer pageSize,
            String name
    ){
        Page<Dish> dishPage = dishService.findByLimit(pageNum,pageSize,name);
        return ResultInfo.success(dishPage);
    }

    //添加菜品
    @PostMapping("/dish")
    public ResultInfo save(@RequestBody Dish dish){
        dishService.save(dish);
        //清理缓存
        String dishKey = "dish_"+dish.getCategoryId();
        redisTemplate.delete(dishKey);

        return ResultInfo.success();
    }

    //回显
    @GetMapping("/dish/{dishId}")
    public ResultInfo findById(@PathVariable("dishId") Long dishId){
        return ResultInfo.success(dishService.findById(dishId));
    }

    //修改
    @PutMapping("/dish")
    public ResultInfo update(@RequestBody Dish dish){
        dishService.update(dish);
        clean("dish_*");
        return ResultInfo.success();
    }



    //修改状态
    @PostMapping("/dish/status/{status}")
    public ResultInfo status(@PathVariable("status")Integer status,@RequestParam List<Long> ids){
        dishService.updateStatus(status,ids);
        clean("dish_*");
        return ResultInfo.success();
    }

    //删除
    @DeleteMapping("/dish")
    public ResultInfo delete(@RequestParam List<Long> ids){
        dishService.deleteById(ids);
        clean("dish_*");
        return ResultInfo.success();
    }

    private void clean(String key) {
        Set keys = redisTemplate.keys(key);
        redisTemplate.delete(keys);
    }

}
